import React, { useState, useEffect, useMemo } from 'react';
import { action_del, action_add, action_edit, action_swap, reload_prop, update_prop } from './cmd';
import { DlgMove, DlgProp } from './ctl';
import { is_empty, loc, KFile, filter_row, WaitUmd, useCmd, obj_str, MCmd, PanelFind, useHigh, Btn, GridTable } from 'sui';

const PropField = ({ title, mod, cur }) => {
    const [open_move, openMove] = useState(false);
    const [open_val, openVal] = useState(false);
    const high = useHigh(210, 100);
    const umd = useCmd();

    useEffect(() => {
        reload_prop(null, v => umd.setValue(v), mod, cur);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [mod, cur]);

    const getRow = useMemo(() => {
        const lst = ["sn", "name"];
        return filter_row(umd.value, lst, umd.filter);
    }, [umd]);

    const act = {
        "add": v => {
            const ret = action_add(v, umd);
            update_prop(umd, mod, ret, cur);
        },
        "edit": v => {
            const ret = action_edit(v, umd);
            update_prop(umd, mod, ret, cur);
        },
        "swap": v => {
            const ret = action_swap(v, umd);
            if (!ret) {
                return;
            }

            update_prop(umd, mod, ret, cur);
        }
    };

    const pact = {
        "add": v => openVal(true),
        "edit": v => openVal(true),
        "swap": v => openMove(true),
    };

    const hDel = (val) => {
        const ret = action_del(val, umd);
        if (!ret) {
            return;
        }

        update_prop(umd, mod, ret, cur, true);
    };

    const hImport = (val) => {
        const set = new Set();
        const ret = [];

        for (let i = 0; i < val.length; i++) {
            const d = val[i];

            const sn = obj_str(d, "sn");
            const name = obj_str(d, "name");

            if (set.has(sn)) {
                umd.setErr(`${loc("l_620")}: ${sn}`);
                return;
            }

            if (!sn || !name) {
                umd.setErr(`${loc("l_276")}, sn: ${sn}, name: ${name}`);
                return;
            }

            if (sn === "sn" || sn === "name") {
                continue;
            }

            ret.push({sn: sn, name: name});
        }

        update_prop(umd, mod, ret, cur);
    };

    const col = [
        {name: loc("l_238"), key: 'e_opt', width: 210, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <MCmd itype="add" hcmd={() => umd.pact(pact, d, "add", {tp: "add", cur: d.index})}/>
                    <MCmd itype="edit" hcmd={() => umd.pact(pact, d, "edit", {tp: "edit", cur: d.index})}/>
                    <MCmd itype="del" hcmd={() => hDel(d)}/>
                    <MCmd itype="swap" hcmd={() => umd.pact(pact, d, "swap", {tp: "swap", cur: d.index})}/>
                </div>
            );
        }},
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_608"), key: 'sn', width: 200},
        {name: loc("l_228"), key: 'name', width: 300},
    ];

    const Right = () => {
        const getAdd = () => {
            if (is_empty(umd.value)) {
                return <Btn hcmd={() => umd.pact(pact, null, "add", {tp: "add", cur: 0})} className="ml-3">{loc("l_239")}</Btn>;
            }

            return null;
        };
        return (
            <div className="inline-flex">
                <KFile umd={umd} title={title} col={["sn", "name"]} row={[
                    {sn: "sn", name: loc("l_608")},
                    {sn: "name", name: loc("l_228")},
                    {sn: "k1", name: `${loc("l_683")}1`},
                    {sn: "k2", name: `${loc("l_683")}2`},
                ]} hcmd={hImport} ext={[
                    {sn: "sn", name: obj_str(cur, "sn")},
                    {sn: "name", name: obj_str(cur, "name")},
                ]}/>
                {getAdd()}
            </div>
        );
    };

    return (
        <div className="flex flex-col">
            <PanelFind cl="green" left={title} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={col} row={getRow} rowHeight={42}/>
            <DlgProp open={open_val} hcmd={v => umd.act(act, v, null, "tp")} setOpen={openVal} data={umd.cur} main={umd.value}/>
            <DlgMove open={open_move} hcmd={v => umd.act(act, v, null, "tp")} setOpen={openMove} data={umd.cur}/>
            <WaitUmd umd={umd}/>
        </div>
    );
};

export {PropField};
